package com.movefeng.hexoblogadmin.service;

import com.github.pagehelper.Page;
import com.movefeng.hexoblogadmin.dao.ArticleDao;
import com.movefeng.hexoblogadmin.dao.CommentDao;
import com.movefeng.hexoblogadmin.dao.UserDao;
import com.movefeng.hexoblogadmin.model.Comment;
import com.movefeng.hexoblogadmin.vo.CommentVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author csp1999
 */
@Service
public class CommentService {

    @Resource
    private CommentDao commentDao;

    @Resource
    private UserDao userDao;

    @Resource
    private ArticleDao articleDao;

    /**
     * 查询评论信息
     * @param searchParam
     * @return
     */
    public Page<CommentVO> queryCommentList(Map<String, Object> searchParam) {
        if ((searchParam.get("searchDatetime")!=null)&&(searchParam.get("searchDatetime")!="")){
            List<String> dateList = (List<String>) searchParam.get("searchDatetime");
            searchParam.put("searchDatetimeStart",dateList.get(0));
            searchParam.put("searchDatetimeEnd",dateList.get(1));
        }
        return commentDao.selectCommentVOList(searchParam);
    }

    /**
     * 批量更新数据库中的评论数据
     * @param commentList
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCommentBatch(List<Comment> commentList) {
        List<Comment> commentsOld = commentDao.selectCommentList();

        // 判断对象是否相等需要在类中重写equels和hashcode
        // 新数据中有的而旧数据中没有的就是需要insert的数据
        List<Comment> toInsert = commentList.stream().filter(x -> !commentsOld.contains(x)).collect(Collectors.toList());
        // 旧数据中有的而新数据中没有的就是需要delete的数据
        List<Comment> toDelete = commentsOld.stream().filter(x -> !commentList.contains(x)).collect(Collectors.toList());

        if (toInsert.size() > 0) {
            commentDao.insertCommentBatch(toInsert);
        }
        if (toDelete.size() > 0) {
            commentDao.deleteCommentBatch(toDelete);
        }
    }

    public void deleteComment(String id) {
        commentDao.deleteComment(id);
    }
}
